<template>
  <el-dialog
    title="详细地址"
    :visible.sync="visible"
    width="1100px"
    class="location-position"
    @closed="reset"
  >

    <div class="search">
      <label for="">筛选地点名称：</label>

      <el-autocomplete
        ref="suggestionBox"
        v-model="addressSeach"
        v-scrollLoad="getLoad"
        class="addressSeach"
        :maxlength="50"
        :debounce="300"
        popper-class="address-autocomplete"
        :fetch-suggestions="queryAddressSearch"
        placeholder="请输入联系地址"
        :trigger-on-focus="false"
        @select="handleSelect"
        @input="handleInput"
      >
        <template slot-scope="{ item }">
          <div class="name">{{ item.value }}</div>
          <span class="addr">{{ item.address }}</span>
        </template>
      </el-autocomplete>
    </div>

    <baidu-map
      v-if="visible"
      ref="BMap"
      class="map"
      :center="BmapConfig.center"
      :zoom="BmapConfig.zoom"
      :scroll-wheel-zoom="true"
      @click="markSelect"
      @ready="mapReady"
    >
      <bm-scale />
      <bm-marker :position="markPoint" :dragging="true" animation="BMAP_ANIMATION_BOUNCE" @dragend="markSelect" />
    </baidu-map>

    <div class="footer">
      <div class="address">
        <label for="">地点名称：</label>
        <el-input v-model="address" placeholder="请输入详细地点名称" />
      </div>
      <div class="btn">
        <el-button
          type="primary"
          @click="confirm"
        >确定</el-button>
        <el-button
          type="default"
          @click="cancel"
        >取消</el-button>
      </div>
    </div>

  </el-dialog>
</template>

<script>
  import { getLocalSearch } from '@/utils/BMap'
  export default {
    name: 'geolocation',
    directives: {
      scrollLoad: {
        bind(el, binding, vnode) {
          const wrapDom = el.querySelector('.el-autocomplete-suggestion__wrap')
          const listDom = el.querySelector('.el-autocomplete-suggestion__list')
          wrapDom.addEventListener(
            'scroll',
            e => {
              const condition =
                listDom.offsetHeight -
                wrapDom.offsetHeight +
                37 -
                0.3 -
                wrapDom.scrollTop
              if (condition < 0 && !vnode.context.loading) {
                // 滚动到底部则执行滚动方法load，binding.value就是v-scrollLoad绑定的值，加()表示执行绑定的方法
                binding.value()
              }
            },
            false
          )
        }
      }
    },
    data() {
      return {
        visible: false,
        markPoint: {},
        location: {},
        BmapConfig: {
          center: { lng: 121.55, lat: 29.88 },
          zoom: 15
        },
        address: '',
        resolve: undefined,
        addressSeach: '',
        addressInfo: {
          page_num: 0,
          page_size: 10
        }
      }
    },
    mounted() {

    },
    methods: {
      open(val) {
        return new Promise(resolve => {
          if (val) {
            this.addressSeach = ''
            this.addressInfo.page_num = 0
            this.location = val
            this.resolve = resolve
            this.address = this.location.address
          }
          this.visible = true
        })
      },

      reset() {
        this.visible = false
      },
      mapReady({ BMap, map }) {
        this.myGeo = new BMap.Geocoder()
        this.$nextTick(() => {
          if (this.location.lat && this.location.lng) {
            this.BmapConfig.center = this.location
            this.markPoint = this.location
          }
        })
      },
      markSelect(val) {
        // console.log(val)
        this.markPoint = val.point
        this.pointToAddress(this.markPoint)
      },
      confirm() {
        const parmas = {
          address: this.address,
          ...this.markPoint
        }
        this.resolve(parmas)
        this.visible = false
      },
      cancel() {
        this.visible = false
      },
      getLoad() {
        console.log('i am load')
        this.addressInfo.page_num++
        this.$refs.suggestionBox.fetchSuggestions()
      },
      handleInput() {
        this.addressInfo.page_num = 0
        console.log('input')
      },
      async queryAddressSearch(queryString, cb) {
        this.getAddressSuggestionList(cb)
      },
      // 输入建议
      async getAddressSuggestionList(cb) {
        const params = {
          page_num: this.addressInfo.page_num,
          page_size: this.addressInfo.page_size,
          queryString: (this.location.provinceName || '') + (this.location.cityName || '') + (this.location.countryName || '') + this.addressSeach,
          city: this.location.cityName
        }
        const res = await getLocalSearch(params)
        if (res && res.results && res.results.length > 0) {
          let list = []
          list = res.results.map(item => ({
            value: item.name || '',
            location: item.location,
            address: item.address || '',
            adcode: item.adcode || '',
            province: item.province || '',
            city: item.city || '',
            area: item.area || ''
          }))
          if (this.location.area && this.location.countryName) {
            list = list.filter(item => (item.area && item.area.includes(this.location.countryName)) || (item.area === ''))
          }
          if (cb) {
            this.suggestionList = list
            cb(this.suggestionList)
          } else {
            this.$nextTick(() => {
              if (params.page_num > 0) {
                this.suggestionList = this.suggestionList.concat(list)
                this.$refs.suggestionBox.suggestions = this.suggestionList
              }
            })
          }
        } else {
          if (cb) {
            this.$message.error('未匹配到正确地址信息，请重新输入详细地址')
            cb([])
          }
        }
      },
      // 地址模糊匹配
      handleSelect(item) {
        const latAndLon = item.location
        if (latAndLon && latAndLon.lat && latAndLon.lng) {
          console.log(latAndLon.lat, latAndLon.lng)
          const point = { lng: latAndLon.lng, lat: latAndLon.lat }
          this.BmapConfig.center = point
          this.markPoint = point
        }
      },
      // 根据坐标逆解析获取地址详细描述
      pointToAddress(point) {
        const _this = this
        this.myGeo.getLocation(point, function(result) {
          if (result) {
            // console.log(result, 111111111)
            _this.province = result.addressComponents.province
            _this.city = result.addressComponents.city
            _this.district = result.addressComponents.district
            let address = ''
            const ssq = _this.province + _this.city + _this.district
            if (result.surroundingPois.length > 0) {
              address = result.address + result.surroundingPois[0].title
            } else {
              address = result.address
            }
            // console.log(address.split(ssq)[1])
            // console.log(_this.point)
            _this.$set(_this, 'addressSeach', address.split(ssq)[1])
          }
        })
      }
    }

  }
</script>

<style lang="scss" scoped>
.search {
  margin-bottom: 10px;
}
.location-position {
  & /deep/ .el-dialog__body {
    display: flex;
    flex-direction: column;
    justify-content: center;
    height: 600px;
  }
}

.map {
  width: 100%;
  flex: 1;
}

.footer {
  display: flex;
  align-items: center;
  justify-content: space-between;
  .address {
    .el-input {
      width: 400px;
    }
  }
  .btn {
    margin-top: 20px;
    text-align: right;
  }
}
.addressSeach {
  & /deep/ .el-input {
    width: 300px;
  }
}
</style>

<style lang="scss">

.address-autocomplete {
  li {
    padding: 7px;
    line-height: normal;
    .addr {
      font-size: 12px;
      color: #b4b4b4;
    }
  }
}
</style>
